import { DeleteOutlined, DragOutlined } from "@ant-design/icons";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css";
import {
	Button,
	Card,
	Checkbox,
	Col,
	Divider,
	Form,
	Input,
	InputNumber,
	Radio,
	Row,
	Select,
	Switch,
	Tabs,
	Typography,
	Upload,
} from "antd";
import React, { useState, useEffect } from "react";
import {
	DragDropContext,
	Draggable,
	type DropResult,
	Droppable,
} from "react-beautiful-dnd";

const { Title } = Typography;

export interface FormField {
	id: number;
	taskId: number;
	fieldId: number;
	fieldType:
		| "text"
		| "number"
		| "select"
		| "image"
		| "file"
		| "textarea"
		| "radio"
		| "checkbox"
		| "richtext";
	fieldLabel: string;
	required: boolean;
	placeholder?: string;
	sort: number;
	createTime?: Date;
	updateTime?: Date;
	deleteTime?: Date | null;
}

interface FormBuilderProps {
	value?: FormField[];
	onChange?: (fields: FormField[]) => void;
}

const FIELD_TYPES = [
	{
		type: "text",
		label: "文本框",
		icon: "📝",
	},
	{
		type: "textarea",
		label: "多行文本",
		icon: "📄",
	},
	{
		type: "number",
		label: "数字输入",
		icon: "🔢",
	},
	{
		type: "select",
		label: "下拉选择",
		icon: "📑",
	},
	{
		type: "radio",
		label: "单选框",
		icon: "⭕",
	},
	{
		type: "checkbox",
		label: "多选框",
		icon: "☑️",
	},
	{
		type: "image",
		label: "图片上传",
		icon: "🖼️",
	},
	{
		type: "file",
		label: "文件上传",
		icon: "📎",
	},
	{
		type: "richtext",
		label: "富文本编辑器",
		icon: "📝",
	},
] as const;

// 生成一个不重复的毫秒级ID
const generateFieldId = () => {
	const timestamp = new Date().getTime();
	const random = Math.floor(Math.random() * 1000); // 生成0-999的随机数
	return parseInt(`${timestamp}${random.toString().padStart(3, "0")}`);
};

export default function FormBuilder({
	value = [],
	onChange,
}: FormBuilderProps) {
	const [editor, setEditor] = useState<IDomEditor | null>(null);
	const [html, setHtml] = useState<string>("");

	// 编辑器配置
	const editorConfig: Partial<IEditorConfig> = {
		placeholder: "请输入内容...",
	};

	// 工具栏配置
	const toolbarConfig: Partial<IToolbarConfig> = {
		excludeKeys: [],
	};

	// 组件销毁时，销毁编辑器
	useEffect(() => {
		return () => {
			if (editor == null) return;
			editor.destroy();
			setEditor(null);
		};
	}, [editor]);

	const [fields, setFields] = useState<FormField[]>(value);
	const [activeTab, setActiveTab] = useState<string>("config");
	const [configForm] = Form.useForm();
	const [previewForm] = Form.useForm();

	const handleDragEnd = (result: DropResult) => {
		console.log("拖拽结束:", result);
		if (!result.destination) {
			console.log("没有目标位置");
			return;
		}

		const { source, destination } = result;
		console.log("源位置:", source);
		console.log("目标位置:", destination);

		if (
			source.droppableId === "fieldTypes" &&
			destination.droppableId === "formFields"
		) {
			const fieldType = FIELD_TYPES[source.index].type;
			const newField: FormField = {
				id: Date.now(),
				taskId: 0,
				fieldId: generateFieldId(),
				fieldType: fieldType,
				fieldLabel: FIELD_TYPES[source.index].label,
				required: false,
				placeholder: "",
				sort: 0,
			};

			const newFields = [...fields];
			newFields.splice(destination.index, 0, newField);
			setFields(newFields);
			onChange?.(newFields);
		} else if (
			source.droppableId === "formFields" &&
			destination.droppableId === "formFields"
		) {
			const newFields = [...fields];
			const [removed] = newFields.splice(source.index, 1);
			newFields.splice(destination.index, 0, removed);
			setFields(newFields);
			onChange?.(newFields);
		}
	};

	const updateField = (fieldId: number, updates: Partial<FormField>) => {
		const newFields = fields.map((field) =>
			field.fieldId === fieldId ? { ...field, ...updates } : field,
		);
		setFields(newFields);
		onChange?.(newFields);
	};

	const removeField = (id: number) => {
		const newFields = fields.filter((field) => field.id !== id);
		setFields(newFields);
		onChange?.(newFields);
	};

	const renderPreviewField = (field: FormField) => {
		const commonProps = {
			label: field.fieldLabel,
			required: field.required,
			placeholder: field.placeholder,
		};

		switch (field.fieldType) {
			case "text":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<Input />
					</Form.Item>
				);
			case "textarea":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<Input.TextArea />
					</Form.Item>
				);
			case "number":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<InputNumber style={{ width: "100%" }} />
					</Form.Item>
				);
			case "select":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<Select
							options={field.options?.map((opt) => ({
								label: opt,
								value: opt,
							}))}
						/>
					</Form.Item>
				);
			case "radio":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<Radio.Group>
							{field.options?.map((opt) => (
								<Radio key={opt} value={opt}>
									{opt}
								</Radio>
							))}
						</Radio.Group>
					</Form.Item>
				);
			case "checkbox":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<Checkbox.Group options={field.options} />
					</Form.Item>
				);
			case "image":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<Upload listType="picture-card">上传图片</Upload>
					</Form.Item>
				);
			case "file":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<Upload>
							<Button>上传文件</Button>
						</Upload>
					</Form.Item>
				);
			case "richtext":
				return (
					<Form.Item {...commonProps} name={field.id}>
						<div
							style={{
								border: "1px solid #d9d9d9",
								borderRadius: "6px",
								zIndex: 100,
							}}
						>
							<Toolbar
								editor={editor}
								defaultConfig={toolbarConfig}
								mode="default"
								style={{ borderBottom: "1px solid #d9d9d9" }}
							/>
							<Editor
								defaultConfig={editorConfig}
								value={html}
								onCreated={setEditor}
								onChange={(value) => setHtml(value)}
								mode="default"
								style={{ height: "300px", overflowY: "hidden" }}
							/>
						</div>
					</Form.Item>
				);
			default:
				return null;
		}
	};

	return (
		<DragDropContext onDragEnd={handleDragEnd}>
			<Row gutter={16}>
				<Col span={6}>
					<Card size="small" title="字段类型" className="h-full">
						<Droppable
							droppableId="fieldTypes"
							isDropDisabled={true}
							renderClone={(provided, snapshot, rubric) => (
								<div
									ref={provided.innerRef}
									{...provided.draggableProps}
									{...provided.dragHandleProps}
									className="border rounded cursor-move bg-white flex flex-col items-center py-2"
								>
									<div className="text-lg mb-1">
										{FIELD_TYPES[rubric.source.index].icon}
									</div>
									<div className="text-xs text-gray-600">
										{FIELD_TYPES[rubric.source.index].label}
									</div>
								</div>
							)}
						>
							{(provided) => (
								<div
									{...provided.droppableProps}
									ref={provided.innerRef}
									className="field-types grid grid-cols-2 gap-2"
								>
									{FIELD_TYPES.map((field, index) => (
										<Draggable
											key={field.type}
											draggableId={field.type}
											index={index}
										>
											{(provided) => (
												<div
													ref={provided.innerRef}
													{...provided.draggableProps}
													{...provided.dragHandleProps}
													className="border rounded cursor-move hover:bg-gray-50 flex flex-col items-center py-2"
												>
													<div className="text-lg mb-1">{field.icon}</div>
													<div className="text-xs text-gray-600">
														{field.label}
													</div>
												</div>
											)}
										</Draggable>
									))}
									{provided.placeholder}
								</div>
							)}
						</Droppable>
					</Card>
				</Col>

				<Col span={18}>
					<Card size="small" className="h-full">
						<Tabs
							activeKey={activeTab}
							onChange={setActiveTab}
							items={[
								{
									key: "config",
									label: "配置",
									children: (
										<div className="form-config">
											<Droppable droppableId="formFields">
												{(provided) => (
													<div
														{...provided.droppableProps}
														ref={provided.innerRef}
														className="form-preview min-h-[200px] p-4"
													>
														{fields.map((field, index) => (
															<Draggable
																key={field.fieldId}
																draggableId={field.fieldId.toString()}
																index={index}
															>
																{(provided) => (
																	<div
																		ref={provided.innerRef}
																		{...provided.draggableProps}
																		className="mb-4"
																	>
																		<Card
																			size="small"
																			className="bg-gray-50"
																			title={
																				<div
																					{...provided.dragHandleProps}
																					className="flex items-center gap-2"
																				>
																					<DragOutlined />
																					<span>
																						{
																							FIELD_TYPES.find(
																								(item) => item.type === field.fieldType,
																							)?.label
																						}
																					</span>
																				</div>
																			}
																			extra={
																				<Button
																					type="text"
																					danger
																					icon={<DeleteOutlined />}
																					onClick={() => removeField(field.id)}
																				/>
																			}
																		>
																			<Form form={configForm} layout="vertical">
																				<Row gutter={16}>
																					<Col span={16}>
																						<Form.Item
																							label="字段标签"
																							required
																							help="这是表单中显示的字段名称"
																						>
																							<Input
																								value={field.fieldLabel}
																								onChange={(e) =>
																									updateField(field.fieldId, {
																										fieldLabel: e.target.value,
																									})
																								}
																								placeholder="请输入字段标签"
																							/>
																						</Form.Item>
																					</Col>
																					<Col span={8}>
																						<Form.Item
																							label="是否必填"
																							help="用户是否必须填写此字段"
																						>
																							<Switch
																								checked={field.required}
																								onChange={(checked) =>
																									updateField(field.fieldId, {
																										required: checked,
																									})
																								}
																								checkedChildren="必填"
																								unCheckedChildren="选填"
																							/>
																						</Form.Item>
																					</Col>
																				</Row>

																				<Form.Item
																					label="提示文本"
																					help="输入框内的提示信息"
																				>
																					<Input
																						value={field.placeholder}
																						onChange={(e) =>
																							updateField(field.fieldId, {
																								placeholder: e.target.value,
																							})
																						}
																						placeholder="请输入提示文本"
																					/>
																				</Form.Item>

																				{(field.fieldType === "select" ||
																					field.fieldType === "radio" ||
																					field.fieldType === "checkbox") && (
																					<Form.Item
																						label="选项列表"
																						required
																						help="输入选项后按回车添加，可拖动调整顺序"
																					>
																						<Select
																							mode="tags"
																							value={field.options || []}
																							onChange={(value) =>
																								updateField(field.fieldId, {
																									options: value,
																								})
																							}
																							placeholder="请输入选项"
																						/>
																					</Form.Item>
																				)}
																			</Form>
																		</Card>
																	</div>
																)}
															</Draggable>
														))}
														{provided.placeholder}
													</div>
												)}
											</Droppable>
										</div>
									),
								},
								{
									key: "preview",
									label: "预览",
									children: (
										<div className="bg-white p-4 rounded">
											<Form
												form={previewForm}
												layout="vertical"
												onFinish={(values) => console.log(values)}
											>
												{fields.map((field) => (
													<div key={field.id}>{renderPreviewField(field)}</div>
												))}
												<Form.Item>
													<Button type="primary" htmlType="submit">
														提交
													</Button>
												</Form.Item>
											</Form>
										</div>
									),
								},
							]}
						/>
					</Card>
				</Col>
			</Row>
		</DragDropContext>
	);
}
